package com.hkc.huakang.hkcpaperless;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.hkc.huakang.hkcpaperless.bin.LoggedInUser;

import org.springframework.security.crypto.bcrypt.BCrypt;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class MainActivity extends AppCompatActivity {
    EditText user_name;
    EditText user_password;
    TextView setting_tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        user_name= (EditText)findViewById(R.id.user_name);
        setting_tv= (TextView)findViewById(R.id.setting_tv);
        user_password= (EditText)findViewById(R.id.user_password);
        Button loginBtn= (Button)findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MysqlConnectResult<LoggedInUser> mysqlConnectResult =  login( user_name.getText().toString(), user_password.getText().toString());
              boolean  rst=  contrastUser(mysqlConnectResult);
              //System.out.println("登录->"+rst);
                if(rst){
                    SharedPreferencesUtils.getInstance().saveUserName(MainActivity.this,user_name.getText().toString());
                    SharedPreferencesUtils.getInstance().saveUserPassWord(MainActivity.this,user_password.getText().toString());
                    Intent  intent=new Intent(MainActivity.this,ListViewActivity.class);
                    startActivity(intent);
                    MainActivity.this.finish();
                }
            }
        });
        setting_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent  intent=new Intent(MainActivity.this,SettingActivity.class);
                startActivity(intent);
            }
        });
        user_password.setText(SharedPreferencesUtils.getInstance().getUserPassWord(this));
        user_name.setText(SharedPreferencesUtils.getInstance().getUserName(this));
    }
    public  boolean  contrastUser(MysqlConnectResult<LoggedInUser> mysqlConnectResult){
        if (mysqlConnectResult instanceof MysqlConnectResult.Success) {
            LoggedInUser data = ((MysqlConnectResult.Success<LoggedInUser>) mysqlConnectResult).getData();
            if(data!=null&& data.getDisplayName()!=null){
                if(BCrypt.checkpw(user_password.getText().toString(),data.getPassword())){
                    Toast.makeText(MainActivity.this,"登录成功！",Toast.LENGTH_LONG).show();
                     return true;
                }else{
                    Toast.makeText(MainActivity.this,"密码错误！",Toast.LENGTH_LONG).show();
                    //return loginResult.setValue(new LoginResult(R.string.passWord_error));
                    return false;
                }
            }else {
                Toast.makeText(MainActivity.this,"用户名不存在！",Toast.LENGTH_LONG).show();
                return  false;
                //loginFormState.setValue(new LoginFormState(R.string.invalid_username, null));
                //loginResult.setValue(new LoginResult( R.string.no_username));
            }
        } else if(mysqlConnectResult instanceof MysqlConnectResult.Error){
            String  errorMessage= ((MysqlConnectResult.Error) mysqlConnectResult).getError().getMessage();
            //loginResult.setValue(new LoginResult(R.string.login_failed));
            Toast.makeText(MainActivity.this,"数据库连接错误！"+errorMessage,Toast.LENGTH_LONG).show();
              return false;
        }

        return false;
    }
    public MysqlConnectResult<LoggedInUser> login(String  username, String password){
        final Exception[] ep = new Exception[1];
        final LoggedInUser[] loggedInUser = {new LoggedInUser()};
        try {
            final CountDownLatch latch = new CountDownLatch(1); // 使用 CountDownLatch 来等待回调完成
            MysqlConnectUtil  mysqlConnectUtil=new   MysqlConnectUtil();
            mysqlConnectUtil.connect(new MysqlConnectUtil.ConnectResult() {
                @Override
                public void onConnectFail(Exception e) {
                    System.out.println("连接失败！");
                    latch.countDown();
                    ep[0] =e;
                }
                @Override
                public void onConnectSuccess() {
                    loggedInUser[0] = mysqlConnectUtil.getUser("select * from  sys_user where  User_name='"+username+"'");
                    //获取现在指针指向的行号，即为resultSet集合中数据的总行数
                    latch.countDown();
                }
            },this);
            latch.await(); // 阻塞等待
            if(ep[0]!=null) {
                return new MysqlConnectResult.Error(ep[0]);
            }else if(loggedInUser[0].getDisplayName()==null||loggedInUser[0].getDisplayName().isEmpty()){
                return new MysqlConnectResult.Error(new IOException("Error logging in" ));
            }
            return new MysqlConnectResult.Success<>(loggedInUser[0]);
        } catch (Exception e) {
            return new MysqlConnectResult.Error(new IOException("Error logging in", e));
        }
    }

}